import 'package:aero_frisbee/app/model/af_user_info_model/af_user_info_model.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_message_detail_view_model.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:url_launcher/url_launcher.dart';

import 'af_message_voice_cell.dart';

class AfMessageCell extends ConsumerStatefulWidget {
  const AfMessageCell({
    super.key,
    required this.message,
  });

  final RCIMIWMessage message;
  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _AfMessageCellState();
}

class _AfMessageCellState extends ConsumerState<AfMessageCell> {
  bool get isSelf {
    return widget.message.direction == RCIMIWMessageDirection.send;
  }

  bool get isImg {
    return widget.message is RCIMIWImageMessage;
  }

  @override
  Widget build(BuildContext context) {
    final userInfo = ref
        .watch(getUserInfoFutureProvider(
            userId: widget.message.senderUserId ?? ''))
        .maybeWhen(
          orElse: () => null,
          data: (data) => data,
        );

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        _onTapMessage(message: widget.message);
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 3),
        child: Row(
          textDirection: isSelf ? TextDirection.rtl : TextDirection.ltr,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 44,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: AspectRatio(
                  aspectRatio: 1,
                  child: CachedNetworkImage(
                    imageUrl: userInfo?.avatarUrl ?? '',
                    fit: BoxFit.fill,
                    placeholder: (context, url) => const Material(
                      color: Color(0xffF2F5F9),
                      child: Center(
                        child: SizedBox(
                          width: 25,
                          height: 25,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: Color(0xffADADAD),
                            backgroundColor: Colors.white,
                          ),
                        ),
                      ),
                    ),
                    errorWidget: (context, url, error) =>
                        const CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Color(0xffADADAD),
                      backgroundColor: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(
              width: 10,
            ),
            Expanded(
              child: Column(
                children: [
                  const SizedBox(
                    height: 10,
                  ),
                  Row(
                    textDirection:
                        isSelf ? TextDirection.rtl : TextDirection.ltr,
                    children: [
                      Flexible(
                        flex: 180,
                        child: Container(
                          decoration: BoxDecoration(
                            color: isImg
                                ? Colors.transparent
                                : (isSelf
                                    ? const Color(0xffDDFB6C)
                                    : Colors.white),
                            borderRadius: isImg
                                ? null
                                : BorderRadius.only(
                                    topLeft: isSelf
                                        ? const Radius.circular(13)
                                        : const Radius.circular(0),
                                    topRight: isSelf
                                        ? const Radius.circular(0)
                                        : const Radius.circular(13),
                                    bottomRight: const Radius.circular(13),
                                    bottomLeft: const Radius.circular(13),
                                  ),
                          ),
                          padding: isImg
                              ? null
                              : const EdgeInsets.only(
                                  top: 10, bottom: 10, left: 10, right: 10),
                          child: DefaultTextStyle(
                            style: const TextStyle(
                              color: Color(0xff0E1117),
                            ),
                            textAlign: TextAlign.left,
                            child: _buildContent(
                              message: widget.message,
                              userInfo: userInfo,
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 50,
                        child: Container(),
                      )
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  _onTapMessage({required RCIMIWMessage message}) {
    if (message is RCIMIWTextMessage) {
    } else if (message is RCIMIWVoiceMessage) {
    } else if (message is RCIMIWImageMessage) {
      final imgPath = message.remote;
      launchUrl(Uri.parse(imgPath!), mode: LaunchMode.inAppWebView);
    } else if (message is RCIMIWFileMessage) {
      final file = message.remote;
      launchUrl(Uri.parse(file!), mode: LaunchMode.inAppWebView);
    }
  }

  _buildContent({required RCIMIWMessage message, AfUserInfoModel? userInfo}) {
    if (message is RCIMIWTextMessage) {
      return _buildTextMsg(message: message);
    } else if (message is RCIMIWVoiceMessage) {
      return _buildVoiceMsg(message: message);
    } else if (message is RCIMIWImageMessage) {
      return _buildImgMsg(message: message);
    } else if (message is RCIMIWFileMessage) {
      return _buildFileMsg(message: message);
    }

    return const Text(
      'The message is not yet realized, please upgrade the version!',
      style: TextStyle(
        color: Color(0xff202020),
        fontWeight: FontWeight.normal,
        fontSize: 14,
      ),
      textAlign: TextAlign.left,
      overflow: TextOverflow.ellipsis,
      maxLines: 1,
    );
  }

  _buildTextMsg({required RCIMIWTextMessage message}) {
    return Text(
      '${message.text}',
      style: const TextStyle(
        color: Color(0xff202020),
        fontWeight: FontWeight.normal,
        fontSize: 14,
      ),
      textAlign: TextAlign.left,
    );
  }

  _buildVoiceMsg({required RCIMIWVoiceMessage message}) {
    return AfMessageVoiceCell(
      message: message,
    );
  }

  _buildImgMsg({required RCIMIWImageMessage message}) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(12),
      child: CachedNetworkImage(
        imageUrl: message.remote ?? '',
        fit: BoxFit.fill,
        placeholder: (context, url) => const Material(
          color: Color(0xffF2F5F9),
          child: Center(
            child: SizedBox(
              width: 25,
              height: 25,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                color: Color(0xffADADAD),
                backgroundColor: Colors.white,
              ),
            ),
          ),
        ),
        errorWidget: (context, url, error) => const CircularProgressIndicator(
          strokeWidth: 2,
          color: Color(0xffADADAD),
          backgroundColor: Colors.white,
        ),
      ),
    );
  }

  _buildFileMsg({required RCIMIWFileMessage message}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        const Text(
          'Please check my file',
          style: TextStyle(
            color: Color(0xff202020),
            fontWeight: FontWeight.normal,
            fontSize: 14,
          ),
          textAlign: TextAlign.left,
        ),
        const SizedBox(
          width: 10,
        ),
        isSelf
            ? Assets.images.chat.chatFileSelect.image(width: 24)
            : Assets.images.chat.chatFileSelect.image(width: 24)
      ],
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(AfMessageCell oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
